package cn.scu.ne04jdemo.service.imp;

import cn.scu.ne04jdemo.dao.TreeNodeDao;
import cn.scu.ne04jdemo.entitiy.TreeNode;
import cn.scu.ne04jdemo.service.TreeNodeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TreeNodeServiceImp extends ServiceImpl<TreeNodeDao, TreeNode> implements TreeNodeService {
    private final TreeNodeDao treeNodeDao;

    public TreeNodeServiceImp(TreeNodeDao treeNodeDao) {
        this.treeNodeDao = treeNodeDao;
    }

    private List<TreeNode> selectChildren(TreeNode node) {
        List<TreeNode> children = treeNodeDao.selectList(new QueryWrapper<TreeNode>().lambda().eq(TreeNode::getParent, node.getId()));
        if (children.isEmpty())
            return children;
        else {
            for (TreeNode child : children) {
                List<TreeNode> treeNodes = selectChildren(child);
                child.setChildren(treeNodes);
            }
        }
        return children;
    }

    @Override
    public TreeNode getTreeNodeByHash(String hashValue) {
        TreeNode rootNode = treeNodeDao.selectOne(new QueryWrapper<TreeNode>().lambda().eq(TreeNode::getName, hashValue));
        if (rootNode != null)
            rootNode.setChildren(selectChildren(rootNode));
        return rootNode;
    }
}
